//
// Created by uncleyang on 9/12/21.
//

#include "Buffer.h"

int Buffer::PeekN(int n, std::string &msg) {
    if(n>(writeIndex-readIndex)){
        msg.append(&(*std::next(data.begin(),readIndex)),writeIndex-readIndex);
        return writeIndex-readIndex;
    }else{
        msg.append(&(*std::next(data.begin(),readIndex)),n);
        return n;
    }
}

int Buffer::Read(std::string &msg,int size) {
    if(size>(writeIndex-readIndex)){
        msg.append(&(*std::next(data.begin(),readIndex)),writeIndex-readIndex);
        int result = writeIndex-readIndex;
        writeIndex=0;
        readIndex=0;
//        data.resize(data.size()/2);
//        data.shrink_to_fit();
        return result;
    }else{
        msg.append(&(*std::next(data.begin(),readIndex)),size);
        readIndex+=size;
        return size;
    }
}

void Buffer::Write(char *start, int len) {
    int leftSize = len;
    char *leftIndex = start;
    while(leftSize>0){
        if(leftSize>data.size()-writeIndex){
            std::copy(leftIndex,leftIndex+data.size()-writeIndex,std::next(data.begin(),writeIndex));
            leftSize-=data.size()-writeIndex;
            leftIndex+=data.size()-writeIndex;
            writeIndex+=data.size()-writeIndex;
            data.resize(2*data.size());
        }else{
            std::copy(leftIndex,leftIndex+leftSize,std::next(data.begin(),writeIndex));
            writeIndex+=leftSize;
            leftSize-=leftSize;
        }
    }
}

int Buffer::PopN(int n) {
    if(n>(writeIndex-readIndex)){
        int ret = writeIndex-readIndex;
        readIndex=writeIndex=0;
        return ret;
    }else{
        readIndex+=n;
        return n;
    }
}
